#!/usr/bin/env bash
# Remote PPT macOS Launcher Wrapper
set -e

DIR="$(cd "$(dirname "$0")/../Resources" && pwd)"
cd "$DIR"

find_python() {
    for cmd in \
        "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3" \
        "/Library/Frameworks/Python.framework/Versions/3.11/bin/python3" \
        "/Library/Frameworks/Python.framework/Versions/3.13/bin/python3" \
        "/opt/homebrew/opt/python-tk@3.12/libexec/bin/python3" \
        "/opt/homebrew/bin/python3" \
        "/usr/local/bin/python3" \
        "$(command -v python3 2>/dev/null || true)"; do
        if [ -n "$cmd" ] && [ -x "$cmd" ]; then
            if "$cmd" -c "import tkinter, venv" 2>/dev/null; then
                echo "$cmd"
                return 0
            fi
        fi
    done
    return 1
}

PYTHON_CMD="$(find_python || true)"

if [ -z "$PYTHON_CMD" ]; then
    if osascript -e 'display dialog "Remote PPT needs a quick one-time runtime setup to run on this Mac. Download and install automatically now?" with title "Remote PPT" buttons {"Cancel", "Install Now"} default button "Install Now"' >/dev/null 2>&1; then
        TMP_PKG="/tmp/remote_ppt_mac_runtime.pkg"
        curl -fsSL "https://www.python.org/ftp/python/3.12.8/python-3.12.8-macos11.pkg" -o "$TMP_PKG"
        osascript -e "do shell script \"installer -pkg '$TMP_PKG' -target /\" with administrator privileges"
        rm -f "$TMP_PKG"
        PYTHON_CMD="$(find_python || true)"
    fi
fi

if [ -z "$PYTHON_CMD" ]; then
    osascript -e 'display dialog "Could not prepare Remote PPT runtime automatically. Please run the 1-shot macOS installer from remote.sparvixainnovations.com/install/macos." with title "Remote PPT" buttons {"OK"} default button "OK" with icon stop'
    exit 1
fi

VENV_DIR="$HOME/Library/Application Support/Remote PPT/venv"
if [ ! -x "$VENV_DIR/bin/python" ]; then
    "$PYTHON_CMD" -m venv "$VENV_DIR"
fi
if ! cmp -s "$DIR/requirements.txt" "$VENV_DIR/installed-requirements.txt" 2>/dev/null; then
    "$VENV_DIR/bin/python" -m pip install --quiet -r "$DIR/requirements.txt"
    cp "$DIR/requirements.txt" "$VENV_DIR/installed-requirements.txt"
fi
if [ "${1:-}" = "--install-dependencies" ]; then exit 0; fi
exec "$VENV_DIR/bin/python" "$DIR/desktop_remote_app.py" "$@"
